import Promise from 'promise';
import validator from 'validator';
import * as ResultMsg from '../constrants/ResultMsg';
import { errorJson, successJson } from '../common/response';
import { checkId, checkDoc, checkDocs } from '../common/check';
import { AudioProxy, TopicProxy } from '../proxy';

export {
  getData,
  add,
  del,
  update,
};

async function getData(req, res, next) {
  const appId = res.locals.appId;
  const all = req.body.all || false;

  const conditions = {};
  const options = { sort: '-create_at' };

  try {
    const docs = await AudioProxy.find(appId, conditions, options);
    successJson(res, res, { data: docs });
  } catch (err) {
    next(err);
  }
}

async function add(req, res, next) {
  const appId = res.locals.appId;
  const type = validator.trim(req.body.type || '');
  const title = validator.trim(req.body.title || '');
  const describe = validator.trim(req.body.describe || '');
  const url = validator.trim(req.body.url || '');

  if (type === '' || title === '' || describe === '' || url === '') {
    return errorJson(req, res, { err: ResultMsg.PARAMS_ERROR });
  }

  const conditions = { $or: [{url}] };
  const options = {};

  try {
    const doc = await AudioProxy.findOne(appId, conditions, options);
    if (doc) return errorJson(req, res, { err: ResultMsg.REPEAT_DATA });

    let data = {
      type,
      title,
      describe,
      url
    };

    const result = await AudioProxy.create(appId, data);
    successJson(req, res, { data: result, msg: ResultMsg.ADDED_SUCCESS });
  } catch (err) {
    next(err);
  }
}

async function del(req, res, next) {
  const appId = res.locals.appId;
  const audioId = req.params.aid;

  try {
    await checkId(audioId);
    await AudioProxy.removeById(appId, audioId);
    successJson(req, res, { msg: ResultMsg.UPDATE_SUCCESS });
  } catch (err) {
    next(err);
  }
}

async function update(req, res, next) {
  const appId = res.locals.appId;
  const audioId = req.params.aid;
  const type = validator.trim(req.body.type || '');
  const title = validator.trim(req.body.title || '');
  const describe = validator.trim(req.body.describe || '');
  const url = validator.trim(req.body.url || '');

  if (type === '' || title === '' || describe === '' || url === '') {
    return errorJson(req, res, { err: ResultMsg.PARAMS_ERROR });
  }

  const data = {
    type,
    title,
    describe,
    url
  }

  try {
    await checkId(audioId);
    await AudioProxy.update(appId, audioId, data);
    successJson(req, res, { msg: ResultMsg.UPDATE_SUCCESS });
  } catch (err) {
    next(err);
  }
}
